/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.lestr.genver.network;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author pibonnin
 */
public abstract class TCPServer {


    private Thread serverProcess;


    private ServerSocket serverSocket;


    private boolean stop;


    private int port;


    public TCPServer() {

        port = 8048;
        serverSocket = null;

        serverProcess = new Thread() {


            @Override
            public void run() {

                while (!stop) {
                    try {

                        final Socket socket = serverSocket.accept();

                        if (socket.isConnected()) {
                            new Thread() {


                                @Override
                                public void run() {

                                    processClient(socket);

                                }// END Method run


                            }.start();
                        }

                    } catch (Exception ex) {
                        Logger.getLogger(TCPServer.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

            }// END Method run


        };

    }// END Constructor


    /**
     * @return Port TCP utilis� par le serveur.
     */
    public int getPort() {

        return port;

    }// END Method getPort


    /**
     * @param Port TCP utilis� par le serveur.
     */
    public void setPort(int port) {

        this.port = port;

    }// END Method setPort


    public void start() throws Exception {

        serverSocket = new ServerSocket(getPort());
        serverProcess.start();

    }// END Method start


    public void stop() throws Exception {

        stop = true;
        serverSocket.close();
        serverSocket = null;

    }// END Method stop


    protected abstract void processClient(Socket socket);

    
}// END Class AstennServer

